package com.app.common;

import com.app.model.AdminUserModel;
import com.app.model.FileModel;
import com.app.model.RecordFileModel;
import com.app.model.UserModel;
import com.app.server.AdminUserService;
import com.app.server.FileService;
import com.app.server.RecordFileService;
import com.app.server.UserService;
import com.app.utils.CommonHelp;
import com.app.utils.TokenUtils;
import com.app.utils.UploadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Slf4j
@RestController
@RequestMapping("/sbbz/file")
public class UploadController {
    @Autowired
    private FileService fileService;

    @Autowired
    private RecordFileService recordFileService;

    @PostMapping("/upload")
    public Result<Object> upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {
        if(!UploadUtils.imageTypeRight(file))
        {
            return Result.error(500,"文件格式错误");
        }
        //上传文件路径
        String path = "";
        path = SystemConstant.DEFAULT_UPLOAD_URL;
        //获得上传文件名
        String fileName = file.getOriginalFilename();
        int lastIndexOf = fileName.lastIndexOf(".");
        String date = getRandomString2(8);
        //获取文件的后缀名 .jpg
        String suffix = fileName.substring(lastIndexOf);
        String suffix2 = fileName.substring(lastIndexOf + 1);
        File filePath = new File(path + File.separator + date + suffix);
        System.out.println(filePath);
        //如果文件目录不存在，创建目录
        if (!filePath.getParentFile().exists()) {
            filePath.getParentFile().mkdirs();
        }
        //获取文件大小
        //将上传文件保存到一个目标文件中
        file.transferTo(filePath);
        String[] suffixType1Arr = SystemConstant.DEFAULT_type1.split(",");
        FileModel fileModel = new FileModel();
        for (int i = 0; i < suffixType1Arr.length; i++) {
            if (suffix2.contains(suffixType1Arr[i])) {
                fileModel.setFileType(1);
            }
        }
        String[] suffixType2Arr = SystemConstant.DEFAULT_type2.split(",");
        for (int i = 0; i < suffixType2Arr.length; i++) {
            if (suffix2.contains(suffixType2Arr[i])) {
                fileModel.setFileType(2);
            }
        }
        String fileURL = SystemConstant.DEFAULT_PDF_SERVICE_URL + date + suffix;
        String[] suffixType3Arr = SystemConstant.DEFAULT_type3.split(",");
        for (int i = 0; i < suffixType3Arr.length; i++) {
            if (suffix2.contains(suffixType3Arr[i])) {
                fileModel.setFileType(4);
                fileModel.setName(file.getOriginalFilename());
                fileModel.setUrl(fileURL);
                fileModel.setCreateTime(CommonHelp.getNowTimestamp());
                fileService.save(fileModel);
                return Result.success(fileModel);
            }
        }
        fileModel.setName(date + suffix);
        fileModel.setUrl(fileURL);
        fileModel.setCreateTime(CommonHelp.getNowTimestamp());
        fileService.save(fileModel);
        return Result.success(fileModel);
    }


    /**
     * 上传文件
     */
    @PostMapping("/uploadApi")
    public Result<Object> uploadApi(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        if(!UploadUtils.imageTypeRight(file))
        {
            return Result.error(500,"文件格式错误");
        }
        //上传文件路径
        String path = "";
        path = SystemConstant.DEFAULT_UPLOAD_URL;
        //获得上传文件名
        String fileName = file.getOriginalFilename();
        int lastIndexOf = fileName.lastIndexOf(".");
        String date = getRandomString2(8);
        //获取文件的后缀名 .jpg
        String suffix = fileName.substring(lastIndexOf);
        String suffix2 = fileName.substring(lastIndexOf + 1);
        File filePath = new File(path + File.separator + date + suffix);
        System.out.println(filePath);
        //如果文件目录不存在，创建目录
        if (!filePath.getParentFile().exists()) {
            filePath.getParentFile().mkdirs();
        }
        //获取文件大小
        //将上传文件保存到一个目标文件中
        file.transferTo(filePath);
        String fileURL = SystemConstant.DEFAULT_PDF_SERVICE_URL + date + suffix;
        String[] suffixType1Arr = SystemConstant.DEFAULT_type1.split(",");
        RecordFileModel recordFileModel = new RecordFileModel();
        for (int i = 0; i < suffixType1Arr.length; i++) {
            if (suffix2.contains(suffixType1Arr[i])) {
                recordFileModel.setFileType(1);
            }
        }
        String[] suffixType2Arr = SystemConstant.DEFAULT_type2.split(",");
        for (int i = 0; i < suffixType2Arr.length; i++) {
            if (suffix2.contains(suffixType2Arr[i])) {
                recordFileModel.setFileType(2);
            }
        }
        recordFileModel.setName(date + suffix);
        recordFileModel.setUrl(fileURL);
        recordFileModel.setCreateTime(CommonHelp.getNowTimestamp());
        recordFileModel.setFilePath(filePath.getPath());
        return Result.success(recordFileModel);
    }

    //可以指定字符串的某个位置是什么范围的值
    public static String getRandomString2(int length) {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(3);
            long result = 0;
            switch (number) {
                case 0:
                    result = Math.round(Math.random() * 25 + 65);
                    sb.append(String.valueOf((char) result));
                    break;
                case 1:
                    result = Math.round(Math.random() * 25 + 97);
                    sb.append(String.valueOf((char) result));
                    break;
                case 2:
                    sb.append(String.valueOf(new Random().nextInt(10)));
                    break;
            }
        }
        return sb.toString();
    }

    @PostMapping("/uploadToLocal")
    public Object uploadToLocal(HttpServletRequest request) throws IOException {
        // 获取文件
        List<MultipartFile> file = ((MultipartHttpServletRequest) request).getFiles("file");
        if (!file.isEmpty()) {
            //上传文件路径
            String path = SystemConstant.DEFAULT_UPLOAD_URL;
            //获得上传文件名
            List<RecordFileModel> recordFileModels = new ArrayList<>();
            for (int i1 = 0; i1 < file.size(); i1++) {
                if(!UploadUtils.imageTypeRight(file.get(i1)))
                {
                    return Result.error(500,"文件格式错误");
                }
                String fileName = file.get(i1).getOriginalFilename();
                assert fileName != null;
                int lastIndexOf = fileName.lastIndexOf(".");
                long time = System.currentTimeMillis();
                String date = "LOCAL_" + time;
                //获取文件的后缀名 .jpg
                String suffix = fileName.substring(lastIndexOf);
                File filePath = new File(path + File.separator + date + suffix);
                //如果文件目录不存在，创建目录
                if (!filePath.getParentFile().exists()) {
                    boolean mkdirs = filePath.getParentFile().mkdirs();
                }
                file.get(i1).transferTo(filePath);
                RecordFileModel recordFileModel = new RecordFileModel();
                String[] suffixType1Arr = SystemConstant.DEFAULT_type4.split(",");
                for (int i = 0; i < suffixType1Arr.length; i++) {
                    if (suffix.contains(suffixType1Arr[i])) {
                        recordFileModel.setName(fileName);
                        recordFileModel.setUrl(SystemConstant.DEFAULT_PDF_SERVICE_URL + date + suffix);
                        recordFileModels.add(recordFileModel);
                    }
                }
            }
            return recordFileModels;
        } else {
            return Result.error(500, "上传失败");
        }

    }
}
